// src/components/sponsorDashboard/mainContent/Table.tsx

import { useState } from "react";
import { LuPanelRightClose, LuPanelRightOpen } from "react-icons/lu";
import { MdSentimentDissatisfied } from "react-icons/md";
import { FaAddressBook } from "react-icons/fa";
import type { SponsorRecord } from "@/types/types";
import SponsorContactsModal from "@/components/popups/sponsorTable/companyContactsByCompanyId/SponsorContactsModal";

interface TableProps {
  sponsors: SponsorRecord[];
  selectedHeaders: string[];
}

interface TableHeader {
  label: string;
  key: keyof SponsorRecord;
  expandable?: boolean;
  expanded?: boolean;
  children?: TableHeader[];
}

const Table = ({
  sponsors,
  selectedHeaders,
}: TableProps) => {
  const [showContactsModal, setShowContactsModal] = useState(false);
  const [selectedSponsorId, setSelectedSponsorId] = useState<number | null>(null);

  const [headers, setHeaders] = useState<TableHeader[]>([
    { label: "Umbrella Code", key: "umbrella_code" },
    { label: "Cocode", key: "company_code" },
    {
      label: "Company Name",
      key: "company_name",
      expandable: true,
      expanded: false,
      children: [
        { label: "Company ID", key: "sponsor_id" },
      ],
    },
    {
      label: "Program",
      key: "program_code",
      expandable: true,
      expanded: false,
      children: [
        { label: "Program ID", key: "program_id" },
        { label: "Program Length", key: "program_length" },
      ],
    },
    { label: "CO-OP Program", key: "coop_program" },
    { label: "Position", key: "position" },
    { label: "Status", key: "status" },
    { label: "Faculty", key: "faculty" },
    { label: "Year", key: "program_year" },
    { label: "Total Amount Per Position", key: "total_amount_per_position" },
    { label: "Sponsorship Cost", key: "sponsorship_cost" },
    { label: "Logo", key: "logo" },
    { label: "Logo Last Updated", key: "logo_last_updated" },
  ]);

  const toggleExpand = (index: number) => {
    const newHeaders = [...headers];
    const header = newHeaders[index];
    if (header.expandable) {
      header.expanded = !header.expanded;
      setHeaders(newHeaders);
    }
  };

  const flatHeaders: TableHeader[] = headers.flatMap((header) => {
    if (header.expandable && header.expanded && header.children) {
      return [header, ...header.children];
    }
    return [header];
  });

  const filteredHeaders = flatHeaders.filter((header) =>
    selectedHeaders.includes(header.key as string)
  );

  const handleCompanyIdClick = (sponsorId: number) => {
    setSelectedSponsorId(sponsorId);
    setShowContactsModal(true);
  };

  return (
    <div className="overflow-x-auto mt-4 px-1 sm:px-4 font-poppins w-full">
      <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-md overflow-hidden border border-gray-200 dark:border-slate-700 min-h-[200px] flex items-center justify-center w-full transition-all duration-300">
        {filteredHeaders.length === 0 ? (
          <div className="flex flex-col items-center justify-center w-full py-16 text-gray-400 dark:text-gray-500">
            <span className="text-5xl mb-4 text-blue-200 dark:text-cyan-900">
              <MdSentimentDissatisfied />
            </span>
            <span className="italic text-xs sm:text-sm md:text-base text-center">
              Please select one or more columns to display.
            </span>
          </div>
        ) : (
          <div className="overflow-x-auto w-full">
            <table className="w-full text-xs sm:text-sm md:text-base border-b border-gray-100 dark:border-slate-700">
              <thead className="sticky top-0 z-10 bg-blue-50 dark:bg-slate-800 border-b-2 border-gray-200 dark:border-slate-700 shadow-sm text-xs sm:text-sm md:text-base transition-all duration-300">
                <tr>
                  {filteredHeaders.map((header, idx) => {
                    const parent = headers.find(
                      (h) =>
                        h.children?.some((child) => child.key === header.key) &&
                        h.expanded
                    );
                    const childKeys = parent?.children?.map((c) => c.key) ?? [];
                    const isLeft = header.key === childKeys[0];
                    const isRight = header.key === childKeys[childKeys.length - 1];
                    const isInside = !!parent;

                    const borderClasses = isInside
                      ? [
                        "border-t-2",
                        "border-b-2",
                        isLeft && "border-l-2 rounded-tl-md rounded-bl-md",
                        isRight && "border-r-2 rounded-tr-md rounded-br-md",
                        "border-blue-400 dark:border-cyan-400 border-dashed",
                      ]
                        .filter(Boolean)
                        .join(" ")
                      : "border-r border-gray-200 dark:border-slate-600";
                    return (
                      <th
                        key={`${header.label}-${idx}`}
                        className={`p-2 sm:p-3 text-left font-extrabold text-gray-800 dark:text-cyan-300 whitespace-nowrap tracking-wide ${borderClasses}`}
                        aria-label={header.label}
                        title={header.label}
                      >
                        <div className="flex items-center justify-between">
                          <span>{header.label}</span>
                          {header.expandable && (
                            <button
                              onClick={() =>
                                toggleExpand(
                                  headers.findIndex((h) => h.key === header.key)
                                )
                              }
                              className="ml-2 hover:scale-125 transition-transform focus:outline-none rounded-full p-1 hover:bg-blue-100 dark:hover:bg-slate-700"
                              tabIndex={-1}
                              aria-label={header.expanded ? `Collapse ${header.label}` : `Expand ${header.label}`}
                            >
                              {header.expanded ? (
                                <LuPanelRightOpen className="text-blue-500 dark:text-cyan-300" size={18} />
                              ) : (
                                <LuPanelRightClose className="text-blue-500 dark:text-cyan-300" size={18} />
                              )}
                            </button>
                          )}
                        </div>
                      </th>
                    );
                  })}
                </tr>
              </thead>
              <tbody>
                {sponsors.length === 0 ? (
                  <tr>
                    <td
                      colSpan={filteredHeaders.length}
                      className="text-center p-8 sm:p-12 text-gray-400 dark:text-gray-500 italic bg-gray-50 dark:bg-slate-900"
                    >
                      <span className="text-5xl mb-4 block text-blue-200 dark:text-cyan-900"><MdSentimentDissatisfied /></span>
                      <span className="italic text-xs sm:text-sm md:text-base text-center">No sponsor records found.</span>
                    </td>
                  </tr>
                ) : (
                  sponsors.map((sponsor, rowIndex) => (
                    <tr
                      key={rowIndex}
                      className={"border-t border-gray-100 dark:border-slate-700 transition-all duration-150 hover:bg-blue-50/60 dark:hover:bg-slate-700/60"}
                    >
                      {filteredHeaders.map((header, colIndex) => {
                        const parent = headers.find(
                          (h) =>
                            h.children?.some((child) => child.key === header.key) &&
                            h.expanded
                        );
                        const childKeys = parent?.children?.map((c) => c.key) ?? [];
                        const isLeft = header.key === childKeys[0];
                        const isRight = header.key === childKeys[childKeys.length - 1];
                        const isInside = !!parent;

                        const cellBorderClasses = isInside
                          ? [
                            "border-t-2",
                            "border-b-2",
                            isLeft && "border-l-2",
                            isRight && "border-r-2",
                            "border-blue-400 dark:border-cyan-400 border-dashed",
                          ]
                            .filter(Boolean)
                            .join(" ")
                          : "border-r border-gray-100 dark:border-slate-700";

                        return (
                          <td
                            key={`${rowIndex}-${colIndex}`}
                            className={`p-2 sm:p-3 text-gray-800 dark:text-gray-100 whitespace-nowrap transition-colors duration-100 ${cellBorderClasses}`}
                          >
                            {/* Special handling for Company ID and Company Name columns */}
                            {header.key === "sponsor_id" ? (
                              <button
                                onClick={() => handleCompanyIdClick(Number(sponsor[header.key]))}
                                className="inline-flex items-center gap-1 px-2 py-1 text-blue-600 hover:text-blue-800 hover:bg-blue-50 rounded-md font-medium transition-all duration-200 cursor-pointer whitespace-nowrap border border-transparent hover:border-blue-200"
                                title={`Click to view contacts for Company ID: ${sponsor[header.key]}`}
                              >
                                <FaAddressBook className="text-xs" />
                                {String(sponsor[header.key] ?? "")}
                              </button>
                            ) : header.key === "company_name" ? (
                              <button
                                onClick={() => handleCompanyIdClick(Number(sponsor.sponsor_id))}
                                className="inline-flex items-center gap-1 px-2 py-1 text-blue-600 hover:text-blue-800 hover:bg-blue-50 rounded-md font-medium transition-all duration-200 cursor-pointer whitespace-nowrap border border-transparent hover:border-blue-200"
                                title={`Click to view contacts for ${String(sponsor[header.key] ?? "")}`}
                              >
                                <FaAddressBook className="text-xs" />
                                {String(sponsor[header.key] ?? "")}
                              </button>
                            ) : (
                              <span title={String(sponsor[header.key] ?? "")} className="block whitespace-nowrap">
                                {String(sponsor[header.key] ?? "")}
                              </span>
                            )}
                          </td>
                        );
                      })}
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        )}
      </div>
      {/* Sponsor Contacts Modal */}
      {showContactsModal && (
        <SponsorContactsModal
          onClose={() => setShowContactsModal(false)}
          sponsorId={selectedSponsorId || undefined}
        />
      )}
    </div>
  );
};

export default Table;